package com.qdxwx.manage.controller.user;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户(前台用户)Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Permissions("user:list")
    @GetMapping("/list.html")
    public String user() {
        return "user/user-list";
    }
    /**
     * 查询用户(前台用户)列表
     */
    @Permissions("user:list")
    @PostMapping("/list.json")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return TableDataInfo.error("登录超时");
        String searchKey = TKString.trim(request.getParameter("searchKey"));
        List<User> list;
        UserQuery query = new UserQuery();
        if (searchKey.length() > 1) {
            if (TKString.isNumber(searchKey)) {
                User user;
                if (TKString.isMobile(searchKey)) {
                    user = userService.getByMobile(searchKey);
                } else {
                    user = userService.get(TKConvert.toLong(searchKey));
                }
                list = new ArrayList<>();
                if (user != null) {
                    list.add(user);
                }
                return TableDataInfo.success(list, list.size());
            } else {
                query.setSearchKey(searchKey);
            }
        }
        query.setRegisterFrom(request.getParameter("registerFrom"));
        query.setIsAvailable(TKConvert.toInteger(request.getParameter("isAvailable"), null));
        list = userService.getList(query, PageRequest.form(request));
        return TableDataInfo.success(list, userService.count(query));
    }
}
